<?php
/**
 * Note: 权限
 * Date: 2018/11/20
 */
namespace App\Models;

use App\Traits\ModelTrait;


class RoleAccess extends Base
{
    use ModelTrait;

    protected $table = 'role_access';

    public $timestamps = false;

    public $fillable = [
        'name',
        'route'
    ];

    /**
     *
     * @return array
     */
    public function format($roles = [])
    {
        if (in_array(1, $roles)
            // 被分配的角色勾选了所有权限
            || RolePermission::whereIn('role_id', $roles)->where('access_id', 1)->exists()) {
            $accessLists = $this->all()->toArray();
        } else {
            $accessLists = $this->leftJoin('role_permissions', 'role_permissions.access_id', '=', 'role_access.id')
                ->whereIn('role_permissions.role_id', $roles)
                ->whereNotNull('role_permissions.access_id')
                ->get()->toArray();
        }

        $data = [];
        foreach ($accessLists as $k => $access) {
            if ($access['route'] === '*') {
                $data['god'] = $access;
                continue;
            }
            list($module,) = explode('.', $access['route']);
            if (!isset($data[$module])) {
                $data[$module]['id'] = $access['id'];
                $data[$module]['name'] = getRouteTranslate($module);
            }
        }

        foreach ($data as $module => $name) {
            foreach ($accessLists as $access) {
                if ($access['route'] === '*' && $module === 'god') continue;

                $route = str_replace('admin.', '', $access['route']);
                if (\Str::startsWith($route, $module.'.')) {
                    $data[$module]['child'][] = $access;
                }
            }
        }
        sort($data);
        return $data;
    }
}
